package lol.clann.bukkit.pluginboot.version;

import lol.clann.bukkit.pluginboot.version.v1_7.MappingSetup_v1_7;
import org.bukkit.Bukkit;
import org.bukkit.Server;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;

/**
 * @author pyz
 * @date 2018/10/5 下午8:37
 */
public class VersionSetup {

    private static final String version = Bukkit.getBukkitVersion();
    /**
     * nms包和obc包里的版本号
     */
    private static final String packageVersion;
    private static final String cbPrefix;
    private static final String nmsPrefix;
    private static final boolean forge;
    private static final Map<Predicate<String>, Runnable> versions = new HashMap<>();

    static {
        boolean isForge;
        try {
            Class.forName("cpw.mods.fml.common.Loader");
            isForge = true;
        } catch (ClassNotFoundException e) {
            isForge = false;
        }
        forge = isForge;
        packageVersion = getPackageVersion();
        cbPrefix = "org.bukkit.craftbukkit." + packageVersion;
        nmsPrefix = "net.minecraft.server." + packageVersion;
        // 1.7的混淆映射
        versions.put(version -> version.startsWith("1.7."), () -> MappingSetup_v1_7.setup());
    }

    public static void setup() {
        for (Map.Entry<Predicate<String>, Runnable> en : versions.entrySet()) {
            if (en.getKey().test(version)) {
                en.getValue().run();
                return;
            }
        }
        DefaultMappingSetup.setup();
    }

    public static boolean isForge() {
        return forge;
    }

    public static String getBukkitVersion() {
        return version;
    }

    public static String packageVersion() {
        return packageVersion;
    }

    public static String getCBPrefix() {
        return cbPrefix;
    }

    public static String getNMSPrefix() {
        return nmsPrefix;
    }

    private static String getPackageVersion() {
        Server server = Bukkit.getServer();
        String obcServerClassName = server.getClass().getName();
        obcServerClassName = obcServerClassName.substring("org.bukkit.craftbukkit.".length());
        obcServerClassName = obcServerClassName.substring(0, obcServerClassName.indexOf("."));
        return obcServerClassName;
    }
}
